﻿namespace EyeOpen.Crypt.Client.Wcf
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using EyeOpen.Crypt.Client.Service;
    using EyeOpen.IO;

    public class EncryptionServiceClient : ClientBase<IEncryptionService>, IEncryptionService
    {
        private EncryptionResult result;

        public EncryptionServiceClient()
        {
        }

        public EncryptionServiceClient(string endpointConfigurationName) :
            base(endpointConfigurationName)
        {
        }

        public EncryptionServiceClient(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }

        public EncryptionServiceClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
        {
        }

        public EncryptionServiceClient(Binding binding, EndpointAddress remoteAddress) :
            base(binding, remoteAddress)
        {
        }

        public event EventHandler<CryptEventArgs> CryptCompleted;

        public EncryptionResult CryptDecrypt(string key, string source)
        {
            BeginDoWork(key, source, DoCrypting, null);
            return result;
        }

        public IAsyncResult BeginDoWork(string key, string source, AsyncCallback callback, object asyncState)
        {
            return Channel.BeginDoWork(key, source, callback, asyncState);
        }

        public EncryptionResult EndDoWork(IAsyncResult asyncresult)
        {
            return Channel.EndDoWork(asyncresult);
        }

        private void DoCrypting(IAsyncResult ar)
        {
            result = EndDoWork(ar);
            var handler = CryptCompleted;
            if (handler != null)
            {
                handler(this, new CryptEventArgs(result));
            }
        }
    }
}
